package handler

import (
	"github.com/gin-gonic/gin"
	"management/api/register"
	"management/inits/model"
	"management/internal/dao"
	"management/pkg"
)

type Res struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

func Login(r *gin.Context) {
	var req register.User
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "参数失败",
			Data:    nil,
		})
		return
	}
	user := model.User{}
	if err = dao.FindUsername(&user, req.Username); err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "用户查询失败",
			Data:    nil,
		})
		return
	}
	if user.ID == 0 {
		r.JSON(400, &Res{
			Code:    400,
			Message: "用户不存在",
			Data:    nil,
		})
		return
	}
	r.JSON(200, &Res{
		Code:    200,
		Message: "登录成功",
		Data:    user.ID,
	})
}

func Upload(r *gin.Context) {
	var req register.Upload
	if err := r.ShouldBind(&req); err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "参数错误",
			Data:    nil,
		})
		return
	}

	// 获取文件，先检查错误
	file, err := r.FormFile("image")
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "获取文件失败",
			Data:    nil,
		})
		return
	}

	// 调用上传函数
	uploadURL, err := pkg.Upload(file)
	if err != nil {
		r.JSON(200, &Res{
			Code:    200,
			Message: "图片上传成功",
			Data:    uploadURL,
		})
	}
}
